#include "adc_voice.h"
#include "OSAL.h"
#include "gpio.h"
#include "clock.h"
#include "adc.h"
#include "log.h"
#include "voice.h"
#include "mcu.h"



uint16 value_t = 9;	//声音值
uint8_t voiceSensitivity = 0; 	//调节声音敏感度
uint16_t adc_debug[6][MAX_SAMPLE_POINT];
static uint8_t channel_done_flag = 0;

uint8 adcDemo_TaskID;

static adc_Cfg_t adc_cfg =
{
	.channel = ADC_BIT(ADC_CH2P_P14),
	.is_continue_mode = FALSE,
	.is_differential_mode = 0x00,
	.is_high_resolution = 0x00,
};

void adcMeasureTask( void );


void adc_Init(uint8 task_id)
{
	adcDemo_TaskID = task_id;
	adcMeasureTask();
}

uint16 adc_ProcessEvent(uint8 task_id,uint16 events)
{
	if(task_id != adcDemo_TaskID)
	{
		return 1;
	}
	if(events & adcMeasureTask_EVT)
	{
		adcMeasureTask();
		return (events ^ adcMeasureTask_EVT);
	}
	
	return 0;
	
}
static void adc_evt(adc_Evt_t * pev)
{
	float value = 0;
    int i = ADC_CH2P_P14;

    if((pev->type != HAL_ADC_EVT_DATA) || (pev->ch < 2))
        return;

    osal_memcpy(adc_debug[pev->ch-2],pev->data,2*(pev->size));
    channel_done_flag |= BIT(pev->ch);

    if(channel_done_flag == adc_cfg.channel)
    {
		value = hal_adc_value_cal((adc_CH_t)i,adc_debug[i-2], pev->size, FALSE,FALSE);										
		if((uint16)(value*1000) > (VOICE_NUM + voiceSensitivity))
		{
			value_t = (uint16)(value*1000);
		}
        channel_done_flag = 0;

    }
}


void adcMeasureTask(void)
{
	int ret;
	bool batt_mode = FALSE;
	uint8_t batt_ch = ADC_CH2P_P14;
	GPIO_Pin_e pin;
	
	if(FALSE == batt_mode)
	{
		ret = hal_adc_config_channel(adc_cfg,adc_evt);
	}
	else
	{
		if((((1 << batt_ch) & adc_cfg.channel) == 0) || (adc_cfg.is_differential_mode != 0x00))
		{
			return;
		}
		pin = s_pinmap[batt_ch];
		hal_gpio_cfg_analog_io(pin,Bit_DISABLE);
		hal_gpio_write(pin,1);
		ret = hal_adc_config_channel(adc_cfg,adc_evt);
		hal_gpio_cfg_analog_io(pin,Bit_DISABLE);
	}
	
	if(ret)
	{
		LOG("ret = %d\n",ret);
		return;
	}
	
	hal_adc_start(INTERRUPT_MODE);
}

